const { Sequelize } = require("sequelize");
const { isRequired } = require("../utils");

module.exports = (sequelize, DataTypes) => {
  const Role = sequelize.define(
    "Role",
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: Sequelize.UUIDV4,
        //是否允许为空
        allowNull: false,
        //是否为主键
        primaryKey: true,
        //备注
        comment: "角色id",
      },
      roleName: {
        type: DataTypes.STRING,
        allowNull: false,
        comment: "角色名称",
        validate: isRequired("角色名称"),
      },
      remark: {
        type: DataTypes.STRING,
        allowNull: true,
        comment: "角色描述",
      },
      parentId: {
        type: DataTypes.UUID,
        comment: "父级id",
        allowNull: true,
      },
    },
    {
      timestamps: true,
      tableName: "system_role",
      createdAt: "createTime",
      updatedAt: "updateTime",
      comment: "角色信息表",
    }
  );
  Role.associate = function (db) {
    // 角色关联用户
    Role.belongsToMany(db.User, {
      through: db.UserRole,
      foreignKey: "roleId",
      as: "users",
    });
    // 角色关联菜单
    Role.belongsToMany(db.Menu, {
      through: db.RoleMenu,
      foreignKey: "roleId",
      as: "menus",
    });
  };

  return Role;
};
